import { _decorator, Component, EventTouch, instantiate, Mask, Node, Prefab, random, Sprite, tween, Vec3 } from 'cc';
import { Card } from './Card';
import { Input } from 'cc';
import { Door } from './Door';
const { ccclass, property } = _decorator;

@ccclass('Game')
export class Game extends Component {
    @property(Prefab)
    public door: Node = null!
    private doorInstance: Node = null!

    //等待栏
    @property(Node)
    public box:Node=null!


    //卡牌容器
    @property(Node)
    public container:Node=null!

    //容器
    @property(Prefab)
    public cardPrefab:Prefab=null!



    private all:{ele:Node,index:number}[]=[]
    //所有卡牌种类
    private allCardVal:number[]=[]

    //等待区的上一张卡牌
    private lastCard: { value:any,  position:any}=null!

    //当前等待区
    private cardsContainer:Node[]=[]

    //所有卡牌种类
    private totalCardType:number=6;

    //卡牌数
    private totalCard:number=30;

    //等待区位置
    private boxPosition:any[]=[
        { x: -275.3, t: 0 },
        { x: -165.10000000000002, t: 0 },
        { x: -54.90000000000002, t: 0 },
        { x: 55.29999999999998, t: 0 },
        { x: 165.5, t: 0 },
        { x: 275.7, t: 0 }
    ]

    //卡牌位置
    // private cardPosition:{x:number,t:number}[]=[
    //     { x: -278.8, t: 249.59999999999997 },
    //     { x: -233.8, t: 249.59999999999997 },
    //     { x: -188.8, t: 249.59999999999997 },
    //     { x: -143.8, t: 249.59999999999997 },
    //     { x: -98.80000000000001, t: 249.59999999999997 },
    //     { x: -53.80000000000001, t: 249.59999999999997 },
    //     { x: -8.800000000000011, t: 249.59999999999997 },
    //     { x: 36.19999999999999, t: 249.59999999999997 },
    //     { x: 81.19999999999999, t: 249.59999999999997 },
    //     { x: 126.19999999999999, t: 249.59999999999997 },
    //     { x: 171.2, t: 249.59999999999997 },
    //     { x: 216.2, t: 249.59999999999997 },
    //     { x: 261.2, t: 249.59999999999997 },
    //     { x: -278.8, t: 131.49999999999997 },
    //     { x: -233.8, t: 131.49999999999997 },
    //     { x: -188.8, t: 131.49999999999997 },
    //     { x: -143.8, t: 131.49999999999997 },
    //     { x: -98.80000000000001, t: 131.49999999999997 },
    //     { x: -53.80000000000001, t: 131.49999999999997 },
    //     { x: -8.800000000000011, t: 131.49999999999997 },
    //     { x: 36.19999999999999, t: 131.49999999999997 },
    //     { x: 81.19999999999999, t: 131.49999999999997 },
    //     { x: 126.19999999999999, t: 131.49999999999997 },
    //     { x: 171.2, t: 131.49999999999997 },
    //     { x: 216.2, t: 131.49999999999997 },
    //     { x: 261.2, t: 131.49999999999997 },
    //     { x: -278.8, t: 13.399999999999977 },
    //     { x: -233.8, t: 13.399999999999977 },
    //     { x: -188.8, t: 13.399999999999977 },
    //     { x: -143.8, t: 13.399999999999977 },
    //     { x: -98.80000000000001, t: 13.399999999999977 },
    //     { x: -53.80000000000001, t: 13.399999999999977 },
    //     { x: -8.800000000000011, t: 13.399999999999977 },
    //     { x: 36.19999999999999, t: 13.399999999999977 },
    //     { x: 81.19999999999999, t: 13.399999999999977 },
    //     { x: 126.19999999999999, t: 13.399999999999977 },
    //     { x: 171.2, t: 13.399999999999977 },
    //     { x: 216.2, t: 13.399999999999977 },
    //     { x: 261.2, t: 13.399999999999977 },
    //     { x: -278.8, t: -104.69999999999999 },
    //     { x: -233.8, t: -104.69999999999999 },
    //     { x: -188.8, t: -104.69999999999999 },
    //     { x: -143.8, t: -104.69999999999999 },
    //     { x: -98.80000000000001, t: -104.69999999999999 },
    //     { x: -53.80000000000001, t: -104.69999999999999 },
    //     { x: -8.800000000000011, t: -104.69999999999999 },
    //     { x: 36.19999999999999, t: -104.69999999999999 },
    //     { x: 81.19999999999999, t: -104.69999999999999 },
    //     { x: 126.19999999999999, t: -104.69999999999999 },
    //     { x: 171.2, t: -104.69999999999999 },
    //     { x: 216.2, t: -104.69999999999999 },
    //     { x: 261.2, t: -104.69999999999999 },
    //     { x: -278.8, t: -222.79999999999995 },
    //     { x: -233.8, t: -222.79999999999995 },
    //     { x: -188.8, t: -222.79999999999995 },
    //     { x: -143.8, t: -222.79999999999995 },
    //     { x: -98.80000000000001, t: -222.79999999999995 },
    //     { x: -53.80000000000001, t: -222.79999999999995 },
    //     { x: -8.800000000000011, t: -222.79999999999995 },
    //     { x: 36.19999999999999, t: -222.79999999999995 },
    //     { x: 81.19999999999999, t: -222.79999999999995 },
    //     { x: 126.19999999999999, t: -222.79999999999995 },
    //     { x: 171.2, t: -222.79999999999995 },
    //     { x: 216.2, t: -222.79999999999995 },
    //     { x: 261.2, t: -222.79999999999995 }
    // ]
    private cardPosition: { x: number, y: number }[] = this.generateCardPositions(5, 13, -278.8, 249.6, 45, 118.1);

    generateCardPositions(rows: number, cols: number, startX: number, startY: number, gapX: number, gapY: number): { x: number, y: number }[] {
        const positions: { x: number, y: number }[] = [];
        for (let row = 0; row < rows; row++) {
            for (let col = 0; col < cols; col++) {
                positions.push({
                    x: startX + col * gapX,
                    y: startY - row * gapY
                });
            }
        }
        return positions;
    }

    getRandomNumber(min:number,max:number,count:number){
        var arr=[]
        for(let i=0;i<count;i++){
            var number=Math.floor(Math.random()*(max-min)+min)
            if(arr.indexOf(number)==-1){
                arr.push(number)
            }else{
                i--
            }
        }
        return arr;
    }


    initGame(currentAllCards?:number[]){
        if(!currentAllCards){
            this.cardsContainer=[]
            this.box.destroyAllChildren()
            this.box.removeAllChildren()
        }
        this.allCardVal=[]
        this.all=[]
        this.container.destroyAllChildren()
        this.container.removeAllChildren()
        let totalCardNum=currentAllCards?currentAllCards.length:this.totalCard
        let randomIndex=this.getRandomNumber(0,this.cardPosition.length,totalCardNum).sort((a,b)=>{return a-b})
        randomIndex.forEach((ele,index)=>{
            let card=instantiate(this.cardPrefab)
            let component=card.getComponent(Card)!
            //生成1-6的卡牌种类
            component.val=currentAllCards?currentAllCards[index]:Math.floor(Math.random()*this.totalCardType+1)
            this.allCardVal.push(component.val)
            component.clickable=randomIndex.indexOf(ele+1)>-1&&(ele+1)%13!==0?false:true
            this.container.addChild(card)
            this.all.push({
                index:ele,
                ele:card
            })
            card.setPosition(new Vec3(0,0,0))
            tween(card).to(Math.random(),{position:new Vec3(this.cardPosition[ele].x,this.cardPosition[ele].y,0)}).call(()=>{
                card.setPosition(new Vec3(this.cardPosition[ele].x, this.cardPosition[ele].y, 0))
                card.on(Input.EventType.TOUCH_START,this.cardclick,this)
            }).start()
            

        })


    }

    //用于处理游戏中牌的点击逻辑，确保只有符合条件的牌才能被点击。
    clickableCheck(node:Node, isBack?: boolean){
        let curPosition={x:node.position.x,y:node.position.y}
        let mapIndex=this.cardPosition.findIndex(ele=>{
            return ele.x==curPosition.x&&ele.y==curPosition.y
        })
        let mapIndex2=this.all.find(ele=>{
            return ele.index==mapIndex
        })
        if(mapIndex>-1&&mapIndex2){
            let index=this.all.findIndex(ele=>{return ele.index==mapIndex})
            if(index-1>=0&&this.all[index-1].index===mapIndex2.index-1||mapIndex==1){
                this.all[index-1].ele.getComponent(Card)!.clickable=isBack?false:true
            }
        }
    }
    //点击卡牌后移动卡牌至等待区域
    moveCard(card:Card,node:Node){
        let currentBox=this.cardsContainer;
        currentBox.push(node)
        this.box.addChild(node)
        let targetPosition=this.boxPosition[currentBox.length-1]
        card.isInWait=true;
        tween(node).to(0.3,{
            position:new Vec3(targetPosition.x,targetPosition.t,0)
        }).call(()=>{
            node.setPosition(new Vec3(targetPosition.x,targetPosition.t,0)
        )
        this.checkMatchingCards();
        }).start();
    }
//三消逻辑处理，点击卡牌后逻辑处理
    checkMatchingCards(){
        
        let cardValues = this.cardsContainer.map(node => {  
            let cardComponent = node.getComponent(Card);  
            if (cardComponent) {  
                return cardComponent.val;  
            }else{
                return null
            }  
        });
        let  valueCount=new Map();
        cardValues.forEach(value=>{
            valueCount.set(value,(valueCount.get(value)||0)+1)
        }) 
        for(let [value,count] of valueCount){
            if(count>=3){
                let matchingIndices:number[]=[];
                cardValues.forEach((cardValue,index)=>{
                    if(cardValue===value){
                        matchingIndices.push(index)
                    }
                })
                let indicesToRemove=matchingIndices.slice(0,3)
                for(let i=indicesToRemove.length-1;i>=0;i--){
                    let index=indicesToRemove[i]
                    let nodeToRemove=this.cardsContainer[index]
                    this.cardsContainer.splice(index,1)                    
                    nodeToRemove.destroy()
                }
                this.rearrangeWaitingCards()
                
                break;
            }

    }
}
// 重新排列等待区卡牌
rearrangeWaitingCards(){
    this.cardsContainer.forEach((node,index)=>{
        let targetPosition=this.boxPosition[index]
        tween(node).to(0.3,{
            position:new Vec3(targetPosition.x,targetPosition.t,0)
        }).call(()=>{
            node.setPosition(new Vec3(targetPosition.x,targetPosition.t,0)
        )
    }).start()

})
}
//撤回上一张卡牌
lastStep(){

    if(this.lastCard===null){
        console.log("没有上一步操作")
    }else{
        let newCard=instantiate(this.cardPrefab)
        newCard.getComponent(Card)!.val=this.lastCard.value
        this.allCardVal.push(this.lastCard.value)
        this.container.addChild(newCard)
        newCard.getComponent(Card)!.clickable=true
        newCard.setPosition(new Vec3(this.lastCard.position.x,this.lastCard.position.t,0))
        this.clickableCheck(newCard,true)
        //删除等待区的最后一张卡牌
        this.cardsContainer[this.cardsContainer.length-1].destroy()
        this.cardsContainer[this.cardsContainer.length-1]=null!
        this.cardsContainer=this.cardsContainer.filter((s)=>{
            return s !== null
        })
        if(!this.cardsContainer.length){
            this.box.destroyAllChildren()
            this.box.removeAllChildren()
        }
        this.lastCard=null!
    }

//     if (this.lastCard && this.cardsContainer.length > 0){
//         let lastCardNode=this.cardsContainer[this.cardsContainer.length-1]
//         let cardComponent=lastCardNode.getComponent(Card);
//         if(cardComponent){
//             cardComponent.clickable=true
//             cardComponent.isInWait=false
//             cardComponent.val=this.lastCard.value
//             this.cardsContainer.pop()
//             this.box.removeChild(lastCardNode)
//             this.rearrangeWaitingCards()
//             this.allCardVal.push(cardComponent.val)     
//             let originalPositionIndex =this.all.findIndex(item => item.ele === lastCardNode);
//             if(originalPositionIndex !== -1){
//                 let originalPosition =this.cardPosition[originalPositionIndex]
//                 lastCardNode.off(Input.EventType.TOUCH_START,this.cardclick,this)
//                 tween(lastCardNode).to(0.3,{
//                     position:new Vec3(originalPosition.x,originalPosition.y,0)
//                 }).call(()=>{
//                     lastCardNode.setPosition(new Vec3(originalPosition.x,originalPosition.y,0)
//                 )
//             }).start()

            
//         }
//         this.lastCard = { value: null, position: null }
//     }
// }
}
//打乱卡牌
randomCards(){
    if(this.allCardVal.length){
        this.initGame(this.allCardVal)
    }
}


    cardclick(e:EventTouch){
        //获得点击卡牌的节点
        let node =e.currentTarget
        let card=node.getComponent(Card)
        if (!card.clickable) {
            return;  // 如果不可点击，直接返回，不执行后续操作
        }
        this.lastCard={
            value:card.val,
            position:{x:node.position.x,t:node.position.y}
        }
        //在卡牌数组里删除被点击的卡牌
        if(this.cardsContainer.length<6&&card.clickable){
            for(let i=0;i<this.allCardVal.length;i++){
                if(this.allCardVal[i]==card.val){
                    this.allCardVal.splice(i,1)
                }
            }
        }
        this.clickableCheck(node)
        card.clickable=false
        this.moveCard(card,node)
    }
    quit(){
        this.initGame()
        let doorInstance=instantiate(this.door)
        this.doorInstance=doorInstance
        this.node.addChild(doorInstance)
        let doorObj=this.doorInstance.getComponent(Door)
        doorObj?.closeDoor()
    }
    start() {
        let doorInstance =instantiate(this.door)
        this.doorInstance=doorInstance
        this.node.addChild(doorInstance)
        let doorObj=this.doorInstance.getComponent(Door)
        doorObj?.closeDoor()
        this.initGame()
        
    }

    update(deltaTime: number) {
        
    }
}

